import { useStore } from "@/store";
import { MutationTypes } from "@/store/player/mutation-types";
import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import {
  defaultRoutePath,
  hadAuthMeta,
  loginRoutePath,
  noAuthMeta
} from "@/router/config";
import { SysActionTypes } from "@/store/sys/action-types";

const routes: Array<RouteRecordRaw> = [
  {
    path: defaultRoutePath,
    name: "Wel",
    meta: noAuthMeta,
    component: () =>
      import(/* webpackChunkName: "wel" */ "../views/Wel/index.vue")
  },
  {
    path: loginRoutePath,
    name: "Login",
    meta: noAuthMeta,
    component: () =>
      import(/* webpackChunkName: "login" */ "../views/Login/index.vue")
  },
  {
    path: "/home",
    name: "Home",
    meta: hadAuthMeta,
    component: () =>
      import(/* webpackChunkName: "home" */ "../views/Home/index.vue")
  },
  {
    path: "/about",
    name: "About",
    meta: noAuthMeta,
    component: () =>
      import(/* webpackChunkName: "about" */ "../views/About.vue")
  }
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
});

router.beforeEach(async (to, from, next) => {
  const store = useStore();
  const meta = to.meta || {};
  // 轻刷新从 store 获取 userInfo
  if (!store.state.userInfo.isLogin) {
    // 如果用户重刷新则, 从 localStorage 里获取 userInfo
    store.commit(MutationTypes.GET_USER_INFO);
    // 系统初始化
    store.dispatch(SysActionTypes.SYS_INIT);
    if (!store.state.userInfo.isLogin) {
      if (meta.isAuth === false) {
        next();
      } else {
        next({
          path: "/login"
        });
      }
      if (store.state.ws) {
        store.state.ws.close();
        store.state.ws = undefined;
      }
      return;
    }
  }
  // 只要有就进入画面
  if (to.path === loginRoutePath) {
    next(defaultRoutePath);
  } else {
    next();
  }
  if (to.path === "/home") {
    // 连接消息
    store.dispatch(SysActionTypes.SYS_SET_WS);
  }
  return;
});

export default router;
